//
//  TwERPJsonAgent.m
//  TwERP
//
//  Created by Xiangyang Li on 12-7-14.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "TwERPJsonAgent.h"
#import "Reachability.h"


@implementation TwERPJsonAgent

static NSString * basicURL=@"https://www.eaat.com.cn:8001/twpart/ERPService/";
static int userid;

+ (NSString *)addUserId:(NSString *)query
{
    if ([query rangeOfString:@"?"].location != NSNotFound)
        return [NSString stringWithFormat:@"%@&userid=%d",query,userid];
    else {
        return [NSString stringWithFormat:@"%@?userid=%d",query,userid];
    }    
    
}

+ (NSString *)executeQuery0:(NSString *)query //net
{
    if(![self isServerReachable]) return nil;
   // NSStringEncoding encoding=CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingDOSChineseSimplif);
    NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000);
    query = [self addUserId:query];
    query = [basicURL stringByAppendingString:query];
    query = [query stringByAddingPercentEscapesUsingEncoding:encoding];
   //  query = [query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    // NSLog(@"[%@ %@] sent %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), query);
   NSError *error = nil;
    
    NSString * ts =[NSString stringWithContentsOfURL:[NSURL URLWithString:query] encoding:encoding error:&error];
    //@"{\"licenseNo\":\"云AL1660\",\"vehId\":14949.0}";
    //
    if (error) NSLog(@"[%@ %@] web error: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), error.localizedDescription);
    return ts;
    
  }


+ (id)executeQuery:(NSString *)query //net
{
    if(![self isServerReachable]) return nil;
    NSStringEncoding encoding=NSUTF8StringEncoding;
    //NSUTF16StringEncoding;
    //CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingDOSChineseSimplif);
  //  NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000);
    // query = [self addUserId:query];
    query = [basicURL stringByAppendingString:query];
    query = [query stringByAddingPercentEncodingWithAllowedCharacters: NSCharacterSet.URLQueryAllowedCharacterSet];
   // query = [query stringByAddingPercentEscapesUsingEncoding:encoding];
    //  query = [query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
   // NSLog(@"[%@ %@] sent %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), query);
    NSError *error = nil;
    
    NSString * ts =[NSString stringWithContentsOfURL:[NSURL URLWithString:query] encoding:encoding error:&error];
    
    if (error) NSLog(@"[%@ %@] web error: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), error.localizedDescription);
    
    
    NSData *jsonData = [ts dataUsingEncoding:NSUTF8StringEncoding];
  //  NSData *jsonData = [ts dataUsingEncoding:encoding];
    
    
    error = nil;
    NSDictionary * results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error] : nil;
    if (error) NSLog(@"[%@ %@] JSON error: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), error.localizedDescription);
    if (error) NSLog(@"[%@ %@] JSON String: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), ts);
    
    return results;

   

}

+ (NSString *) postJson:(NSDictionary *)entityData ToURL: (NSString *)urlString //net
{
        if(![self isServerReachable]) return nil;
  //  urlString = [self addUserId:urlString];
    NSURL *url = [NSURL URLWithString:[basicURL stringByAppendingString:urlString]];
  // NSLog(@"[%@ %@] sent %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), url);
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
 //   NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
    
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
   NSLog(@"entity %@",entityData);
    NSError *error;
    NSData *postData = [NSJSONSerialization dataWithJSONObject:entityData options:0 error:&error];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[postData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];
    NSURLResponse* response = [[NSURLResponse alloc] init];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000);
    NSString * retStr=[[NSString alloc] initWithData:data encoding:encoding];
   NSLog(@"Response:%@ \n %@ \n %@", response, error,retStr);
 //   retStr = @"success";
    return retStr;

}
 /*
+ (NSString *) postJson:(NSDictionary *)entityData ToURL: (NSString *)urlString //net
{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration
                                                defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setHTTPMethod:@"POST"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    // choose the right type for your value.
    // NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000);
    
    NSData *postData = [NSJSONSerialization dataWithJSONObject:entityData options:0 error:nil];
    [request setURL:[NSURL URLWithString:[basicURL stringByAppendingString:urlString]]];
     [request setHTTPBody:postData];
    
    __block NSString * text =@"";
    NSURLSessionDataTask * dataTask =[session dataTaskWithRequest:request
                                                       completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                           NSLog(@"Response:%@ %@\n", response, error);
                                                           if(error == nil)
                                                           {
                                                               text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
                                                               NSLog(@"Data = %@",text);
                                                               
                                                           } else {
                                                               text = error.localizedDescription;
                                                           }
                                                           
                                                       }];
         [dataTask resume];
    
 
    
    while (text.length == 0 && text != nil) {
        [NSThread sleepForTimeInterval:2.0f];
    }
    NSLog(@"Data = %@",text);
    return  text;
}
*/
+ (NSString *)postFileToServer:(NSURL *)localUrl  //net
{
    //return [self postFileToServer2:localUrl];
    
        if(![self isServerReachable]) return nil;
    //Get path to file.

    NSString *imagePath 	=[localUrl path];   
    NSString *fileName = [localUrl lastPathComponent];
    
    // create request
    NSURL *url = [NSURL URLWithString:[basicURL stringByAppendingString:@"fileSave.aspx"]];
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    	//Set Params                                    
    [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
    [request setHTTPShouldHandleCookies:NO];
    [request setTimeoutInterval:30];
    [request setHTTPMethod:@"POST"];
    
	//Create boundary, it can be anything
    NSString *boundary = @"------WebKitFormBoundary4QuqLuM1cE5lMwCy";

    // set Content-Type in HTTP header
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [request setValue:contentType forHTTPHeaderField: @"Content-Type"];
    
    // post body
    NSMutableData *body = [NSMutableData data];
    
    //Populate a dictionary with all the regular values you would like to send.
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithCapacity:11];
    [parameters setValue:fileName forKey:@"fileName"];
    
    // add params (all params are strings)
    for (NSString *param in parameters) {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"%@\r\n", [parameters objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
    }
    
  
    
    // add image data and compress to send if needed.
 /*   CGFloat compression         = 0.9f;
    CGFloat maxCompression = 0.1f;
    int maxFileSize             = 250*1024;
   */ 
    NSData *imageData = [[NSData alloc] initWithContentsOfFile:imagePath];
    /*
    while ([imageData length] > maxFileSize && compression > maxCompression)
    {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation([UIImage imageNamed:imagePath], compression);
    }
    */
    
    //Assuming data is not nil we add this to the multipart form
    if (imageData) {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n", fileName] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:imageData];
        [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    }
    
    //Close off the request with the boundary
    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    // setting the body of the post to the request
    [request setHTTPBody:body];
    
    //  NSLog(@"request %@",request);
    
    NSURLResponse* response;
    NSError* error;
    
    
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];    
    
    //returnString = @"success";
    NSLog(@"respons %@",returnString);
    NSLog(@"error %@",error);
    
    return returnString;
    
      
}
+ (NSString *)postFileToServer2:(NSURL *)localUrl  //net
{
    if(![self isServerReachable]) return nil;
    //Get path to file.
    
    NSString *imagePath 	=[localUrl path];
    NSString *fileName = [localUrl lastPathComponent];
    NSString *basicURL2 =@"http://www.eaat.com.cn:8001/twpart/ERPService/";
    // create request
    NSURL *url = [NSURL URLWithString:[basicURL2 stringByAppendingString:@"fileSave.jsp"]];
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    //Set Params
    [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
    [request setHTTPShouldHandleCookies:NO];
    [request setTimeoutInterval:30];
    [request setHTTPMethod:@"POST"];
    
	//Create boundary, it can be anything
    NSString *boundary = @"------WebKitFormBoundary4QuqLuM1cE5lMwCy";
    
    // set Content-Type in HTTP header
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [request setValue:contentType forHTTPHeaderField: @"Content-Type"];
    
    // post body
    NSMutableData *body = [NSMutableData data];
    
    //Populate a dictionary with all the regular values you would like to send.
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithCapacity:11];
    [parameters setValue:fileName forKey:@"fileName"];
    
    // add params (all params are strings)
    for (NSString *param in parameters) {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"%@\r\n", [parameters objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
    }
    
    
    
    // add image data and compress to send if needed.
    /*   CGFloat compression         = 0.9f;
     CGFloat maxCompression = 0.1f;
     int maxFileSize             = 250*1024;
     */
    NSData *imageData = [[NSData alloc] initWithContentsOfFile:imagePath];
    /*
     while ([imageData length] > maxFileSize && compression > maxCompression)
     {
     compression -= 0.1;
     imageData = UIImageJPEGRepresentation([UIImage imageNamed:imagePath], compression);
     }
     */
    
    //Assuming data is not nil we add this to the multipart form
    if (imageData) {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n", fileName] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithString:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:imageData];
        [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    }
    
    //Close off the request with the boundary
    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    // setting the body of the post to the request
    [request setHTTPBody:body];
    
    //  NSLog(@"request %@",request);
    
    NSURLResponse* response;
    NSError* error;
    
    
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    
    //returnString = @"success";
    NSLog(@"respons %@",returnString);
    NSLog(@"error %@",error);
    
    return returnString;
    
    
}

+ (void)getFileFromServer:(NSURL *)localUrl   //net
{
        if(![self isServerReachable]) return;
    
   // NSString *imagePath 	=[localUrl path];   
    NSString *fileName = [localUrl lastPathComponent];
    
    // create request
    NSURL *url = [NSURL URLWithString:[basicURL stringByAppendingFormat:@"UploadFiles/%@",fileName]];
   // NSLog(@"[download from: %@", url);
    NSData * fileData =[[NSData alloc] initWithContentsOfURL:url];
    [fileData writeToURL:localUrl atomically:YES];
    
}


+ (NSDictionary *) loginUser:(NSString *)loginName WithPassword:(NSString *)password  //登录
{
    NSString *request = [NSString stringWithFormat:@"login.aspx?loginName=%@&password=%@",loginName,password];
    return [self executeQuery:request];
}

+ (NSDictionary *)  getVehicleByCphm:(NSString *)cphm   //按车牌找车
{
    NSString *request = [NSString stringWithFormat:@"getVehicleByCphm.aspx?cphm=%@",cphm];
    return [self executeQuery:request];
}
+ (NSDictionary *)  getGongdanById:(int)gdId
{
    NSString *request = [NSString stringWithFormat:@"getGongdanById.aspx?gdId=%d",gdId];
    return [self executeQuery:request];
}
+ (NSArray *)  getGongdanListByCphm:(NSString *)cphm   //车辆工单历史
{
    NSString *request = [NSString stringWithFormat:@"getGongdanListOfVehicle.aspx?cphm=%@",cphm];
    return [self executeQuery:request];
}

+ (NSArray *)  getPartListByKeyword:(NSString *)keyword  //零件定义
{
    NSString *request = [NSString stringWithFormat:@"getPartListByKeword.aspx?kewyword=%@",keyword];
    return [self executeQuery:request];
}

+ (NSString *) gdNo
{
    NSString *request = @"gdNo.aspx";
    return [[self executeQuery:request] valueForKey:@"gdNo"];

}
static NSString * cpHeader;

+ (NSString *)getCpHeader  //车牌字头
{
   
     NSString *request = @"getCpHeader.aspx";
       
    if(cpHeader == nil)
        cpHeader = [[self executeQuery:request] valueForKey:@"cpHeader"];
       // @"粤C";
    return cpHeader;

}
+ (NSArray *)getAllCpHeaders              //车牌字头
{
    NSString *request = @"getAllCpHeaders.aspx";
    return [self executeQuery:request];
}
+ (NSArray *)getLabourListByKeyword:(NSString *)keyword //查询工时项目
{
    NSString *request = [NSString stringWithFormat:@"getLabourListByKeyword.aspx?keyword=%@",keyword];
    return [self executeQuery:request];
}
+ (NSArray *)getLabourListByCategoryId:(int)categoryId //浏览工时项目
{
    NSString *request = [NSString stringWithFormat:@"getLabourListByCategoryId.aspx?categoryId=%d",categoryId];
    return [self executeQuery:request];
}

+ (NSArray *)getCategoryOfGd  //工单维修分类
{

     NSString *request = @"getCategoryOfGd.aspx";
     return [[self executeQuery:request] valueForKey:@"gdCategory"];

   
}
+ (NSArray *)getTgxmUrl // 促销推广项目
{
    NSString *request = @"getTgxmUrl.aspx";
    NSArray *queryStrings=[[self executeQuery:request] valueForKey:@"tgxmUrl"];
    NSMutableArray *urls=[[NSMutableArray alloc] initWithCapacity:queryStrings.count];
     NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000);
    for (NSString * qstr in queryStrings) {
       
     
        NSString * query = [basicURL stringByAppendingString:qstr];
        query = [query stringByAddingPercentEscapesUsingEncoding:encoding];
        NSURL * url=[NSURL URLWithString:query];
        [urls addObject:url];
     //   NSLog(@"tgxm:%@",url);
    }
    return urls;
    
}
+ (NSArray *)getJpxmUrl //精品展示项目
{
    NSString *request = @"getJpxmUrl.aspx";
    NSArray *queryStrings=[[self executeQuery:request] valueForKey:@"jpxmUrl"];
    NSMutableArray *urls=[[NSMutableArray alloc] initWithCapacity:queryStrings.count];
    NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000);
    for (NSString * qstr in queryStrings) {
        
        
        NSString * query = [basicURL stringByAppendingString:qstr];
        query = [query stringByAddingPercentEscapesUsingEncoding:encoding];
        NSURL * url=[NSURL URLWithString:query];
        [urls addObject:url];
       // NSLog(@"jpxm:%@",url);
    }
    return urls;

    
}


+ (int) idOfEntityType:(NSString *)className //新纪录id
{

    NSString *request = [NSString stringWithFormat:@"entityID.aspx?entityType=%@",className];
    id iid =[[self executeQuery:request] valueForKey:@"id"];
 
    return [iid integerValue];
     
}


+ (NSString *) commitEntity:(NSDictionary *)entity
{
    NSString *entityName =[entity objectForKey:@"entityName"];
    //NSLog(@"entityDict:%@",entity);

    NSString *request = [NSString stringWithFormat:@"entity/%@.aspx",entityName];
    NSString * responsString =[self postJson:entity  ToURL:request];
    return responsString;
}

+ (void) setHost:(NSString *)hostOrIP
{
    
    if([hostOrIP rangeOfString:@":"].location == NSNotFound)
        basicURL =  [NSString stringWithFormat:@"https://%@:443/twpart/ERPService/",hostOrIP];
    else 
        basicURL = [NSString stringWithFormat:@"http://%@/twpart/ERPService/",hostOrIP];
  /*
    NSString * ts =@"{\"name\":\"粤E\"}";
    
    NSStringEncoding encoding = NSUTF8StringEncoding;
    
     //CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000);
    NSLog(@"%@", ts);
    
    // NSData *jsonData = [ts dataUsingEncoding:NSUTF8StringEncoding];
    NSData *jsonData = [ts dataUsingEncoding:encoding];
    
    
    NSError *error = nil;
    NSDictionary * results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error] : nil;
    if (error) NSLog(@"[%@ %@] JSON error: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), error.localizedDescription);
    if (error) NSLog(@"[%@ %@] JSON String: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), ts);
    else NSLog(@"data:%@",results);
    */
}
+ (void) setUserId:(int) idOfUser
{
    userid = idOfUser;
}
+ (int) getUserId
{
    return userid;
}
+ (NSString *)getBasicUrl
{
    return basicURL;
}
+ (NSString *)printGjd:(int)entityId
{
    NSString *request = [NSString stringWithFormat:@"printGjd.aspx?entityId=%d",entityId];
    return [self executeQuery0:request];
    
   
}
+ (NSString *)printJsd:(int)entityId
{
    NSString *request = [NSString stringWithFormat:@"printJsd.aspx?entityId=%d",entityId];
    return [self executeQuery0:request];
    
    
}
static bool reachable = YES;
+ (void) initReachability
{
    // allocate a reachability object
    ;
    Reachability* reach = [Reachability reachabilityWithHostname:[[NSURL URLWithString:basicURL] host]];
    
    // set the blocks
    reach.reachableBlock = ^(Reachability*reach)
    {
        NSLog(@"REACHABLE!");
        reachable = YES;
    };
    
    reach.unreachableBlock = ^(Reachability*reach)
    {
        NSLog(@"UNREACHABLE!");
        reachable = NO;
    };
    
    // start the notifier which will cause the reachability object to retain itself!
    [reach startNotifier];
}


+(BOOL) isServerReachable
{
//    BOOL nok=YES;
    
      return reachable;
}

@end
